//
// Created by wangyg98 on 2025/4/11.
//

#include "enemy.h"
#include "constants.h"
#include "put_image.h"

Enemy::Enemy(const std::string& path, int num, int interval): Character(path, "enemy", num, interval) {

    //加载敌人角色阴影
    loadimage(&img_enemy_shadow, _T("D:\\Clion Project\\TeyvatSurvivor\\img\\shadow_enemy.png"));

    //敌人生成边界
    enum class SpawnEdge{
        Up = 0,
        Down,
        Left,
        Right
    };

    //将敌人放置在边界的随机位置
    SpawnEdge edge = (SpawnEdge)(rand()%4);

    switch (edge) {
        case SpawnEdge::Up:
            enemy_pos.x = rand() % g_window_width;
            enemy_pos.y = -ENEMY_HIGHT;
            break;
        case SpawnEdge::Down:
            enemy_pos.x = rand() % g_window_width;
            enemy_pos.y = g_window_hight + ENEMY_HIGHT;
            break;
        case SpawnEdge::Left:
            enemy_pos.x = -ENEMY_WIDTH;
            enemy_pos.y = rand() % g_window_hight;
            break;
        case SpawnEdge::Right:
            enemy_pos.x = g_window_width + ENEMY_WIDTH;
            enemy_pos.y = rand() % g_window_hight;
            break;
        default:
            break;
    }
}

void Enemy::Move(const Player &player) {
    const POINT & player_position = player.getPlayerPos();
    dir_x = player_position.x - enemy_pos.x;
    dir_y = player_position.y - enemy_pos.y;
    double len_dir = sqrt(dir_x*dir_x + dir_y*dir_y);
    if(len_dir!=0){
        double normalized_x = dir_x / len_dir;
        double normalized_y = dir_y / len_dir;
        enemy_pos.x += ENEMY_SPEED * normalized_x;
        enemy_pos.y += ENEMY_SPEED * normalized_y;
    }
}

void Enemy::Draw(int delta) {
    int pos_shadow_x = enemy_pos.x + (ENEMY_WIDTH/2 - SHADOW_WIDTH/2);
    int pos_shadow_y = enemy_pos.y + ENEMY_HIGHT - 24;
    put_image_alpha(pos_shadow_x, pos_shadow_y, &img_enemy_shadow);

    this->SetFacingLeft(dir_x);
    this->Play(enemy_pos.x, enemy_pos.y, delta);
}

bool Enemy::CheckPlayerCollision(const Player &player) {
    //将敌人位置等效为点，判断点是否在玩家矩形内
    POINT  check_pos = {enemy_pos.x + ENEMY_WIDTH/2, enemy_pos.y + ENEMY_HIGHT/2};

    bool is_overlap_x = check_pos.x >= player.getPlayerPos().x && check_pos.x <= (player.getPlayerPos().x+player.getPlayerWidth());
    bool is_overlap_y = check_pos.y >= player.getPlayerPos().y && check_pos.y <= (player.getPlayerPos().y+player.getPlayerHeight());
    return is_overlap_x && is_overlap_y;
}

bool Enemy::CheckBulletCollision(const Bullet &bullet) {
    bool is_overlap_x = bullet.bullet_pos.x >= enemy_pos.x && bullet.bullet_pos.x <= (enemy_pos.x+ENEMY_WIDTH);
    bool is_overlap_y = bullet.bullet_pos.y >= enemy_pos.y && bullet.bullet_pos.y <= (enemy_pos.y+ENEMY_WIDTH);

    return is_overlap_x && is_overlap_y;
}

void Enemy::Hurt() {
    alive = false;
}

bool Enemy::CheckAlive() {
    return alive;
}

